<?php
// +----------------------------------------------------------------------
// | 小说系统 [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\common\controller\Admin;
use Think\Cache;
use think\Db;
class Thirdchapter extends Admin {

	public function _initialize() {
		parent::_initialize();
		$this->setMenu();
		$this->model_id = $model_id = $this->request->param('model_id')?$this->request->param('model_id'):96;
		$list            = Db::connect("database.db_config_two")->name('Model')->where('id',$model_id)->column('*', 'id');

		if (empty($list[$model_id])) {
			return $this->error("无此模型！");
		} else {
			$this->modelInfo = $list[$model_id];
			$this->model =  Db::connect("database.db_config_two")->name($this->modelInfo['name']);
		}
		$this->assign('model_id', $model_id);
		$this->assign('model_list', $list);
		
	}

	/**
	 * 章节列表
	 * @return [html] [章节内容]
	 * @author netlife <40150501@qq.com>
	 */
	public function index($id) {		
			if (!$id) {
				return $this->error("非法操作！");
			}
			$info = $this->model->find($id);
			
			if (!$info) {
				return $this->error($this->model->getError());
			}
			$info['model_id'] = $this->modelInfo['id'];
			
			//建议本章生成推广文案
			$suggestid = $info['suggestid']?$info['suggestid']:config('suggestid');
			
			/***默认强关章节****/
			$uid = session('user_auth.uid');
			//$focus = Db::connect("database.db_config_two")->name('chapter_focus')->where(array('uid'=>$uid,'articleid'=>$id))->value('focuschapter');
			//$focuschapter = $focus?$focus:($info['focuschapter']?$info['focuschapter']:config('agent_guanzhu'));
            $focuschapter ='';
			//获取授权用户组
			$access = config('cartoon_access');
			//获取当前用户组
			$group = session('user_auth.group');

			//章节重新排序
			/*
			$droplist = Db::connect("database.db_config_two")->name('chapter')->where(array('status'=>1,'articleid'=>$id))->field('id,chapterorder')->order('chapterorder ASC')->select();
			if($droplist){
				foreach ($droplist as $k=>$v){
					$o = $k+1;
					if($o!=$v['chapterorder']){
						Db::connect("database.db_config_two")->name('chapter')->where("id=".$v["id"])->setField('chapterorder', $o);
					}
				}
			}*/

			/***章节列表***/
        //$chapterlist = Db::connect("database.db_config_two")->name('third_chapter')->where(array('articleid'=>$id))->field('id,chaptername,chapterorder,chaptertype,size,isvip,saleprice')->order('chapterorder ASC')->paginate(config('list_rows'));
        $chapterlist = Db::connect("database.db_config_two")->name('third_chapter')->where(array('articleid'=>$id))->field('id,chaptername,chapterorder,chaptertype,size,isvip,saleprice')->order('id ASC')->paginate(config('list_rows'));

        /*chengz   20201013   添加章节订阅数*/
            $item = $chapterlist->items();
			/*
			foreach ($item as $k1=>$v1){
                $item[$k1]['sub'] = Db::connect("database.db_config_two")->name('subscription')->where('chapterid','=',$v1['id'])->count();
            }*/
            /*chengz   添加章节订阅数结束 */
			$data = array(
				'articleid'       => $id,
				'page'       => input('page')?input('page'):1,
				'info'       => $info,
				'focuschapter'=> $focuschapter,
				'suggestid'=> $suggestid,
				'chapterlist' => $chapterlist,
				'group'       => $group,
				'access'       => $access,
                'items'        =>$item,
			);

			$this->assign($data);
			$this->setMeta("[".$info['title']."]".$this->modelInfo['title'] ."章节列表");
			return $this->fetch();
		
	}

	/**
	 * 内容添加
	 * @author netlife <40150501@qq.com>
	 */
	public function add() {
		$articleid = $this->request->param('articleid');

		$info = Db::connect("database.db_config_two")->name('third_novel')->where("id",$articleid)->find();
		$addorup = visit_addorup($info['update_time']);

		if (IS_POST) {
			//发表者UID
			$this->param['uid'] = session("user_auth.uid");
			//字数
			$this->param['size'] = get_count_content($this->param['content']);
			/*****2020.1.4增加本月更新字数 本月更新天数  开始****/
			$monthsize = $addorup['month']?$this->param['size']:($info['monthsize']+ $this->param['size']);
			if (1 < $addorup['month']) {
				$premonthsize = 0;
				$premonthupds = 0;
				$monthupds = 0;
			}
			else if ($addorup['month'] == 1) {
				$premonthsize = $info['monthsize'];
				$premonthupds = $info['monthupds'];
				$monthupds = 0;
			}

			if ($addorup['day']) {
				$monthupds = $info['monthupds']+1;
			}
			/*****2020.1.4增加本月更新字数 本月更新天数 结束****/

			//是否有金币
			if( $this->param['isvip'] &&$this->param['size']){
				$this->param['saleprice'] = round($this->param['size']/1000*config('wordsperegold'));
			}
			//章节序号
			$chapterorder = Db::connect("database.db_config_two")->name('third_chapter')->where(array('articleid'=>$this->param['articleid']))->count();
			$this->param['chapterorder'] = $chapterorder+1;

			$this->param['articlename'] = get_novel($articleid,'title');
			
			$result = $this->model->save($this->param);	
			if ($result) {
				$chapterId = $this->model->getLastInsID();

				//更新小说章节内容
				$ocontent['chapterid'] = $chapterId;
				$ocontent['content'] = $this->param['content'];

				//数据分表开启的时候
				if(config('partition')){
					$rule = [
						'type' => 'mod', // 分表方式
						'num'  => 10     // 分表数量
					];
					Db::connect("database.db_config_two")->name("third_novel_content")->partition(['chapterid' => $chapterId], "chapterid", $rule)->insert($ocontent);
				}else{
					Db::connect("database.db_config_two")->name("third_novel_content")->insert($ocontent);
				}

				//更新小说总字数  总章节数
				Db::connect("database.db_config_two")->name('third_novel')->where(array('id'=>$articleid))->update(array('lastvolumeid'=>$chapterId,'lastvolume'=>$this->param['chaptername'],'chapter'=>$this->param['chapterorder'],'size'=>array('exp', '`size`+'.$this->param['size']),'monthsize'=>$monthsize,'premonthsize'=>$premonthsize,'monthupds'=>$monthupds,'premonthupds'=>$premonthupds));

				//记录行为
				action_log('add_third_chapter', 'chapter',$chapterId, session('user_auth.uid'));
				return $this->success("添加成功！", url('admin/chapter/index', array('model_id' =>96,'id' => $this->param['articleid'])));
			} else {
				return $this->error($this->model->getError(), url('admin/chapter/index', array('model_id' =>96,'id' => $this->param['articleid'])));
			}
		} else {
			
			$info = array(
				'model_id' => $this->modelInfo['id'],
			);
			$data = array(
				'articleid'       => $articleid,
				'info'       => $info,
				'fieldGroup' => $this->getField($this->modelInfo),
			);			
			
			$this->assign($data);
			$this->setMeta("添加" . $this->modelInfo['title']);
			return $this->fetch('thirdchapter/edit');
		}
	}

	/**
	 * 内容修改
	 * @author netlife <40150501@qq.com>
	 */
	public function edit($id) {
		$articleid = $this->request->param('articleid');
		$novelinfo = Db::connect("database.db_config_two")->name('third_novel')->where("id",$articleid)->find();
		$info = Db::connect("database.db_config_two")->name('third_chapter')->where('id='.$id)->find();
		if (IS_POST) {
			
			//字数			
			$this->param['size'] = get_count_content($this->param['content']);
			$beforesize  = $info['size'];
			$chaptersize = $this->param['size'];
			//是否有金币
			if( $this->param['isvip'] && $this->param['size']){
				$this->param['saleprice'] = round($this->param['size']/1000*config('wordsperegold'));
			}
			
			
			//数据分表开启的时候
			if(config('partition')){
				$rule = [
					'type' => 'mod', // 分表方式
					'num'  => 10     // 分表数量
				];
				Db::connect("database.db_config_two")->name('third_novel_content')->partition(['chapterid' => $id], "chapterid", $rule)->where('chapterid='.$id)->cache('chaptercontent'.$id)->setField('content', $this->param['content']);
			}else{
				$content = Db::connect("database.db_config_two")->name('third_novel_content')->where('chapterid='.$id)->find();
				if($content){
					Db::connect("database.db_config_two")->name('third_novel_content')->where('chapterid='.$id)->cache('chaptercontent'.$id)->setField('content', $this->param['content']);
				}else{
					$ocontent['chapterid'] = $id;
					$ocontent['content'] = $this->param['content'];
					Db::connect("database.db_config_two")->name("third_novel_content")->insert($ocontent);
				}
				
			}
			
			unset($this->param['content']);

			//$result = $this->model->save($this->param, array('id'=> $id));
			$result = Db::connect("database.db_config_two")->name('third_chapter')->where('id', $id)->cache('chapterinfo'.$id)->update($this->param);
			
			if ($result !== false) {
				//记录行为
				action_log('update_third_chapter', 'third_chapter', $id, session('user_auth.uid'),$info);
				
				$subdaysize = 0;
				$subweeksize = 0;
				$submonthsize = 0;
				$subsize = 0;
				$tmpvar = explode("-", date("Y-m-d"));
				$daystart = mktime(0, 0, 0, (int) $tmpvar[1], (int) $tmpvar[2], (int) $tmpvar[0]);
				$monthstart = mktime(0, 0, 0, (int) $tmpvar[1], 1, (int) $tmpvar[0]);
				$tmpvar = date("w");
				
				if ($tmpvar == 0) {
					$tmpvar = 7;
				}

				$weekstart = $daystart;

				if (1 < $tmpvar) {
					$weekstart -= ($tmpvar - 1) * 86400;
				}
				
				$clastupdate = intval($info["update_time"]);

				if ($daystart <= $clastupdate) {
					$subdaysize += $beforesize - $chaptersize;
				}

				if ($weekstart <= $clastupdate) {
					$subweeksize += $beforesize - $chaptersize;
				}

				if ($monthstart <= $clastupdate) {
					$submonthsize += $beforesize - $chaptersize;
				}

				$subsize += $beforesize - $chaptersize;
				//$newdaysize = ($subdaysize < intval($article->getVar("daysize", "n")) ? intval($article->getVar("daysize", "n")) - $subdaysize : 0);
				//$newweeksize = ($subweeksize < intval($article->getVar("weeksize", "n")) ? intval($article->getVar("weeksize", "n")) - $subweeksize : 0);
				$newmonthsize = ($submonthsize < intval($novelinfo["monthsize"]) ? intval($novelinfo["monthsize"]) - $submonthsize : 0);

				$newsize = ($subsize < intval($novelinfo["size"])?intval($novelinfo["size"]) - $subsize : 0);

				//更新小说总字数
				if($info["size"] != $this->param['size']){

					Db::connect("database.db_config_two")->name('third_novel')->where(array('id'=>$articleid))->update(array('monthsize'=>$newmonthsize,'size'=>$newsize));
				}

				return $this->success("更新成功！", url('admin/thirdchapter/index', array('model_id' =>96,'id'=>$articleid)));
			} else {
				return $this->error($this->model->getError(), url('admin/thirdchapter/edit', array('model_id' => 96,'id'=>$articleid)));
			}
		} else {
			if (!$id) {
				return $this->error("非法操作！");
			}
			$info = $this->model->find($id);
			//数据分表开启的时候
			if(config('partition')){
				$rule = [
					'type' => 'mod', // 分表方式
					'num'  => 10     // 分表数量
				];
				$content = Db::connect("database.db_config_two")->name('third_novel_content')->partition(['chapterid' => $id], "chapterid", $rule)->where('chapterid='.$id)->value('content');
			}else{
				$content = Db::connect("database.db_config_two")->name('third_novel_content')->where('chapterid='.$id)->value('content');
			}
			$content = html_entity_decode($content);
			if (!$info) {
				return $this->error($this->model->getError());
			}
			$info['model_id'] = $this->modelInfo['id'];
			$data             = array(
				'articleid'       => $articleid,
				'info'       => $info,
				'content'       => $content,
				'fieldGroup' => $this->getField($this->modelInfo),
			);
			$this->assign($data);
			$this->setMeta("编辑" . $this->modelInfo['title']);
			return $this->fetch();
		}
	}



	/**
	 * 内容删除
	 * @author netlife <40150501@qq.com>
	 */
	public function del() {
		$id = $this->getArrayParam('id');
		$articleid = $this->getArrayParam('articleid');
		
		if (empty($id)) {
			return $this->error("非法操作！");
		}
		
		
		$map['id'] = array('IN', $id);
		
		//删除字数
		$chapter= Db::connect("database.db_config_two")->name('third_chapter')->where($map)->select();
		

		$size = 0;
		if($chapter){
			foreach ($chapter as $k=>$v){
				if(in_array($v["status"],array(1,2))){
					$size +=$v["size"];
				}
			}
		}
		//更新小说总字数
		if($size){
			Db::connect("database.db_config_two")->name('third_novel')->where(array('id'=>$articleid[0]))->update(array('size'=>array('exp', '`size`-'.$size)));
		}
		
		$result = $this->model->where($map)->delete();

		if (false !== $result) {
			//记录行为
			//action_log('delete_chapter', 'chapter', $result, session('user_auth.uid'));
			foreach ($id as $ko=>$vo){
				action_log('delete_chapter','chapter',$vo,session('user_auth.uid'),$chapter[$ko]);
			}
			return $this->success("删除成功！");
		} else {
			return $this->error("删除失败！");
		}
	}

	//草稿
	public function draft() {
		$map = array();
		$map['status'] = 3;
		$map['publishtime'] = 0;
		$keyword = input('keyword');
		if($keyword){
			$map['chaptername'] = array("LIKE", "%$keyword%");
		}
		
		$list = Db::connect("database.db_config_two")->name('third_chapter')->where($map)->order("id DESC")->paginate($this->modelInfo['list_row']);
		
		$data = array(
			'list' => $list,
			'keyword' => $keyword,
			'page' => $list->render(),
		);
		
		
		$this->assign($data);
		$this->setMeta("草稿管理");
		return $this->fetch();
	}

	//定时章节
	public function timing() {
		$map = array();
		$map['status'] = 3;
		$map['publishtime'] = array(">",0);
		$keyword = input('keyword');
		if($keyword){
			$map['chaptername'] = array("LIKE", "%$keyword%");
		}
		
		$list = Db::connect("database.db_config_two")->name('third_chapter')->where($map)->order("id DESC")->paginate($this->modelInfo['list_row']);
		
		$data = array(
			'list' => $list,
			'keyword' => $keyword,
			'page' => $list->render(),
		);
		
		
		$this->assign($data);
		$this->setMeta("定时章节管理");
		return $this->fetch();
	}
	
	//待审章节
	public function chapter() {
		//$status = input('status');
		$map = array();
		$map['status'] = 2;
		$keyword = input('keyword');
		if($keyword){
			$map['chaptername|articlename'] = array("LIKE", "%$keyword%");
		}
		
		$list = Db::connect("database.db_config_two")->name('third_chapter')->where($map)->order("id DESC")->paginate($this->modelInfo['list_row']);
		
		$data = array(
			'list' => $list,
			'keyword' => $keyword,
			'page' => $list->render(),
		);
		
		
		$this->assign($data);
		$this->setMeta("待审章节");
		return $this->fetch();
	}


	//驳回章节
	public function reject() {
		//$status = input('status');
		$map = array();
		$map['status'] = 4;
		$keyword = input('keyword');
		if($keyword){
			$map['chaptername|articlename'] = array("LIKE", "%$keyword%");
		}
		
		$list = Db::connect("database.db_config_two")->name('third_chapter')->where($map)->order("id DESC")->paginate($this->modelInfo['list_row']);
		
		$data = array(
			'list' => $list,
			'keyword' => $keyword,
			'page' => $list->render(),
		);
		
		
		$this->assign($data);
		$this->setMeta("驳回章节");
		return $this->fetch();
	}
	/*****设置强关章节***/
	public function focuschapter() {
		if(IS_GET){
			$focuschapter = input('focuschapter');
			$articleid = input('articleid');
			if($focuschapter&&$articleid){
				$res = Db::connect("database.db_config_two")->name('third_novel')->where('id',$articleid)->update(['focuschapter' =>$focuschapter]);
				if (false !== $res) {
					return $this->success("操作成功！");
				} else {
					return $this->error("操作失败！！");
				}
			}
			
		}
		
		
	}

	/**
	 * 设置状态
	 * @author netlife <40150501@qq.com>
	 */
	public function status() {
		$map['id'] = $id;
		$result    = $this->model->where($map)->setField('status', $status);
		if (false !== $result) {
			return $this->success("操作成功！");
		} else {
			return $this->error("操作失败！！");
		}
	}

	/**
	 * 设置置顶
	 * @author netlife <40150501@qq.com>
	 */
	public function settop($id, $is_top) {
		$map['id'] = $id;
		$result    = $this->model->where($map)->setField('is_top', $is_top);
		if (false !== $result) {
			return $this->success("操作成功！");
		} else {
			return $this->error("操作失败！！");
		}
	}

	/**
	 * 获取字段信息
	 * @return array 字段数组
	 * @author netlife <40150501@qq.com>
	 */
	protected function getField() {
		$field_group = parse_config_attr($this->modelInfo['attribute_group']);

		$map['model_id'] = $this->modelInfo['id'];
		if ($this->request->action() == 'add') {
			$map['is_show'] = array('in', array('1', '2'));
		} elseif ($this->request->action() == 'edit') {
			$map['is_show'] = array('in', array('1', '3'));
		}

		//获得数组的第一条数组
		$rows    = [];
		$row =Db::connect("database.db_config_two")->name('Attribute')->field('*,remark as help,type,extra as "option"')->where($map)->order('group_id asc, sort asc')->select();
		foreach ($row as $key => $value) {
			if (in_array($value['type'],array('checkbox','radio','select','bool'))) {
				$value['option'] = parse_field_attr($value['extra']);
			} elseif ($value['type'] == 'bind') {
				$extra = parse_field_bind($value['extra'], '', $value['model_id']);
				//var_dump($extra);
				$option = array();
				foreach ($extra as $k => $v) {
					$option[$v['id']] = $v['title_show'];
				}
				$value['option'] = $option;
			}
			$rows[$value['id']] = $value;
		}
		if (!empty($rows)) {
			foreach ($rows as $key => $value) {
				$list[$value['group_id']][] = $value;
			}
			foreach ($field_group as $key => $value) {
				$fields[$value] = isset($list[$key]) ? $list[$key] : array();
			}
		}else{
			$fields = array();
		}
		return $fields;
	}

	/**
	 * 创建搜索
	 * @return [array] [查询条件]
	 */
	protected function buildMap($search_key) {
		$map  = array();
		$data = $this->request->param();
		foreach ($data as $key => $value) {
			if ($value) {
				if ($key == 'keyword') {
					$map[$search_key] = array("LIKE", "%$value%");
				} elseif ($key == 'category') {
					$map['category_id'] = $value;
				} elseif ($key == 'create_time') {
					$map['create_time'] = array('BETWEEN', array(strtotime($value[0]), strtotime($value[1])));
				} else {
					$map[$key] = $value;
				}
			}
		}
		
		if (isset($map['page'])) {
			unset($map['page']);
		}
		if (isset($map['model_id'])) {
			unset($map['model_id']);
		}
		$this->assign($data);
		return $map;
	}

	/**
	 * 检测需要动态判断的文档类目有关的权限
	 *
	 * @return boolean|null
	 *      返回true则表示当前访问有权限
	 *      返回false则表示当前访问无权限
	 *      返回null，则会进入checkRule根据节点授权判断权限
	 *
	 * @author 朱亚杰  <xcoolcc@gmail.com>
	 */
	protected function checkDynamic() {
		$model_id = $this->request->param('model_id');
		if (IS_ROOT) {
			return true; //管理员允许访问任何页面
		}
		$models = model('AuthGroup')->getAuthModels(session('user_auth.uid'));
		if (!$model_id) {
			return false;
		} elseif (in_array($model_id, $models)) {
			//返回null继续判断操作权限
			return null;
		} else {
			return false; //无权限
		}
		return false;
	}
	
	
    
	public function api_get_chapter() {
		$chapterid = input('id');
		$chaptername = input('chaptername');

		//数据分表开启的时候
		if(config('partition')){
			$rule = [
				'type' => 'mod', // 分表方式
				'num'  => 10     // 分表数量
			];
			$content = Db::connect("database.db_config_two")->name("novel_content")->partition(['chapterid' => $chapterid], "chapterid", $rule)->value('content');
		}else{
			$content = Db::connect("database.db_config_two")->name('novel_content')->where("chapterid=".$chapterid)->value('content');
		}
		echo json_encode(["title"=>$chaptername,"content"=>html_entity_decode($content)]);
		exit();
	}

	/******章节排序******/
	public function drop() {
		$articleid= input('id');

		if (IS_POST) {
			$articleid= input('id');
			$sort= $_REQUEST["sort"];
			
			if($sort){
				foreach ($sort as $k=>$v){
					Db::connect("database.db_config_two")->name('third_chapter')->where('id='.$v)->setField('chapterorder', $k+1);
				}
				return $this->success("排序成功！", url('admin/chapter/index', array('model_id' =>1,'id'=>$articleid)));
			}else{
				return $this->error("参数错误", url('admin/chapter/drop', array('model_id' => $this->model_id,'id'=>$articleid)));
			}
		}

		$chapterlist = Db::connect("database.db_config_two")->name('third_chapter')->where('articleid = '.$articleid)->order('chapterorder ASC')->select();
		$this->assign('articleid',$articleid);
		$this->assign('chapterlist',$chapterlist);
		$this->setMeta("章节排序");
		return $this->fetch();
	}
	
	//获取所有章节

	public function get_chapters() {
		$bookid = input('articleid');

		if(Cache::get('chapterlist-'.$bookid)){
			$chapter = Cache::get('chapterlist-'.$bookid);
		}else{
			$chapter = Db::connect("database.db_config_two")->name('third_chapter')->where(['articleid'=>$bookid,'status'=>1])->field('id,chaptername,chaptertype,update_time,isvip,saleprice')->page('0,100')->order('id ASC')->select();
			Cache::set('chapterlist-'.$bookid,$chapter,600);
		}

		header('Content-type: text/json'); 		
		echo json_encode($chapter);
		exit();
	}
	
}